package com.nq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nq.common.ServerResponse;
import com.nq.common.entity.vo.StStockTickerDetailsVo;
import com.nq.dao.StLimitUpStockMapper;
import com.nq.dao.StockDzMapper;
import com.nq.dao.stock.StStockMapper;
import com.nq.pojo.StLimitUpStock;
import com.nq.pojo.StockDz;
import com.nq.pojo.StockDzPo;
import com.nq.pojo.vo.StLimitUpStockVo;
import com.nq.service.StockDzService;
import com.nq.stock.entity.StStock;
import com.nq.stock.service.IStStockTickerService;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.SymmetricCryptoUtil;
import com.nq.utils.task.tsanghi.StocksComponent;
import com.nq.vo.stock.StockDzDetailsVo;
import com.nq.vo.stock.StockDzVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author Administrator
* @description 针对表【stock_dz】的数据库操作Service实现
* @createDate 2022-12-03 17:09:01
*/
@Service
@Slf4j
public class StockDzServiceImpl extends ServiceImpl<StockDzMapper, StockDz>
    implements StockDzService{
    @Autowired
    private StockDzMapper stockDzMapper;
    @Autowired
    private StLimitUpStockMapper limitUpStockMapper;
    @Autowired
    private StStockMapper stockMapper;
    @Resource
    private StocksComponent stocksComponent;
    @Autowired
    private IStStockTickerService stStockTickerService;

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public ServerResponse getDzList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<StockDz> list = stockDzMapper.selectList(new QueryWrapper<StockDz>().eq("is_show", 1));

        ArrayList<StockDzVo> stockDzVos = new ArrayList<>();
        for (StockDz dz : list) {
            StockDzVo dzVo = new StockDzVo();
            BeanUtils.copyProperties(dz, dzVo);
            // 获取股票实时数据
            StStockTickerDetailsVo stStockTickerDetailsVo = stStockTickerService.queryDetails(dz.getStockGid(), dz.getStockCode());
            if (null != stStockTickerDetailsVo) {
                dzVo.setRealPrice(stStockTickerDetailsVo.getData().getPrice());
            } else {
                dzVo.setRealPrice(dz.getDiscount());
            }
            dzVo.setPrice(dz.getDiscount());
            stockDzVos.add(dzVo);
        }

        PageInfo pageInfo = new PageInfo(stockDzVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse addByAdmin(String market, String stockCode, String stockNum,
                                     String password, String startTime, String endTime, String discount, Integer time) {
        if (stockCode == null || stockCode.equals("")||market == null || market.equals("") || discount == null|| discount.equals("")||
                 startTime == null || startTime.equals("")||endTime == null || endTime.equals("") || StringUtils.isBlank(stockNum) || StringUtils.isBlank(password)){
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }

        QueryWrapper<StStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", stockCode);
        queryWrapper.eq("market", market);
        StStock stock = stockMapper.selectOne(queryWrapper);

        if (stock == null){
            return ServerResponse.createByErrorMsg("股票不存在！");
        }

        StockDz dz = stockDzMapper.selectByMarketAndCode(stockCode, market);
        if (null != dz) {
            return ServerResponse.createByErrorMsg("该股票已配置， 可查询修改有效期！");
        }


        StockDz stockDz = new StockDz();
        stockDz.setStockName(stock.getName());
        stockDz.setStockCode(stock.getCode());
        stockDz.setStockType(stock.getMarket());
        stockDz.setStockGid(stock.getMarket());
        stockDz.setStockPlate(stock.getMarket());
        stockDz.setIsLock(0);
        stockDz.setIsShow(1);
        stockDz.setAddTime(new Date());
        stockDz.setSpreadRate(BigDecimal.ZERO);
        stockDz.setIncreaseRatio(BigDecimal.ZERO);
        stockDz.setStockNum(Integer.valueOf(stockNum));
        stockDz.setTimes(time);
        stockDz.setPassword(SymmetricCryptoUtil.encryptPassword(password));

        // 设置时区 - 因为美国3月11日到11月7日处于夏令时，是GMT-4 其余时间是GMT-5
        Date start = DateTimeUtil.strToDate(startTime);
        Date end = DateTimeUtil.strToDate(endTime);
        stockDz.setStartTime(start);
        stockDz.setEndTime(end);
        // 价格
        stockDz.setDiscount(new BigDecimal(discount));
        int res = stockDzMapper.insert(stockDz);
        if (res > 0) {
            return ServerResponse.createBySuccessMsg("Added successfully");
        }
        return ServerResponse.createByErrorMsg("Failed to add");
    }

    @Override
    public ServerResponse getDzListByAdmin(int pageNum, int pageSize, String Keywords) {
        PageHelper.startPage(pageNum, pageSize);
        List<StockDz> dzList = stockDzMapper.selectList(new QueryWrapper<StockDz>().like(StringUtils.isNotBlank(Keywords), "stock_code", Keywords).orderByDesc("id"));
        for (StockDz stockDz : dzList) {
            String password = stockDz.getPassword();
            String decryptPassword = SymmetricCryptoUtil.decryptPassword(password);
            stockDz.setPassword(decryptPassword);
        }

        PageInfo pageInfo = new PageInfo(dzList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse updByAdmin(StockDzPo po) {

        StockDz model = new StockDz();
        BeanUtils.copyProperties(po, model);

        // 设置时区 - 因为美国3月11日到11月7日处于夏令时，是GMT-4 其余时间是GMT-5
        Date start = DateTimeUtil.strToDate(po.getStartTime());
        Date end = DateTimeUtil.strToDate(po.getEndTime());

        model.setStartTime(start);
        model.setEndTime(end);
        String password = model.getPassword();
        model.setPassword(SymmetricCryptoUtil.encryptPassword(password));
        return stockDzMapper.updateById(model) > 0 ? ServerResponse.createBySuccess("Modified Successfully") : ServerResponse.createByErrorMsg("Modification Failed");
    }

    @Override
    public ServerResponse deleteByAdmin(String id) {
        int res =  stockDzMapper.deleteById(id);
        if (res > 0) {
            return ServerResponse.createBySuccess("Deleted successfully");
        }
        return ServerResponse.createByErrorMsg("Delete Failed");
    }

    @Override
    public ServerResponse addLimitUpStock(String market, String stockCode, String password, Integer stockNum, String startTime, String endTime) {
        if (stockCode == null || stockCode.equals("")||market == null || market.equals("") ||
                startTime == null || startTime.equals("")||endTime == null || endTime.equals("") || StringUtils.isBlank(password)){
            return ServerResponse.createByErrorMsg("Parameters cannot be empty.");
        }

        QueryWrapper<StStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", stockCode);
        queryWrapper.eq("market", market);
        StStock stock = stockMapper.selectOne(queryWrapper);

        if (stock == null){
            return ServerResponse.createByErrorMsg("股票不存在！");
        }

        QueryWrapper<StLimitUpStock> dzQueryWrapper = new QueryWrapper<>();
        dzQueryWrapper.eq("stock_code", stockCode);
        dzQueryWrapper.eq("market", market);
        StLimitUpStock stLimitUpStock = limitUpStockMapper.selectOne(dzQueryWrapper);
        if (null != stLimitUpStock) {
            return ServerResponse.createByErrorMsg("该股票已配置， 可查询修改有效期！");
        }


        StLimitUpStock upStock = new StLimitUpStock();
        upStock.setMarket(market);
        upStock.setStockName(stock.getName());
        upStock.setStockCode(stock.getCode());
        upStock.setIsLock(0);
        upStock.setIsShow(1);
        upStock.setStockNum(stockNum);
        upStock.setAddTime(new Date());
        upStock.setPassword(SymmetricCryptoUtil.encryptPassword(password));

        Date start = DateTimeUtil.strToDate(startTime);
        Date end = DateTimeUtil.strToDate(endTime);

        upStock.setStartTime(start);
        upStock.setEndTime(end);
        int res = limitUpStockMapper.insert(upStock);
        if (res > 0) {
            return ServerResponse.createBySuccessMsg("Added successfully");
        }
        return ServerResponse.createByErrorMsg("Failed to add");
    }

    @Override
    public ServerResponse deleteLimitUpStock(String id) {
        return limitUpStockMapper.deleteById(id) > 0 ? ServerResponse.createBySuccessMsg("Deleted successfully") : ServerResponse.createByErrorMsg("Failed to delete");
    }

    @Override
    public ServerResponse updateLimitUpStock(StLimitUpStockVo model) {
        StLimitUpStock limitUpStock = new StLimitUpStock();
        limitUpStock.setId(model.getId());
        limitUpStock.setStockNum(model.getStockNum());
        String password = model.getPassword();
        limitUpStock.setPassword(SymmetricCryptoUtil.encryptPassword(password));

        // 设置时区 - 因为美国3月11日到11月7日处于夏令时，是GMT-4 其余时间是GMT-5
        Date start = DateTimeUtil.strToDate(model.getStartTime());
        Date end = DateTimeUtil.strToDate(model.getEndTime());
        limitUpStock.setStartTime(start);
        limitUpStock.setEndTime(end);
        return limitUpStockMapper.updateById(limitUpStock) > 0 ? ServerResponse.createBySuccessMsg("Updated successfully") : ServerResponse.createByErrorMsg("Failed to update");
    }

    @Override
    public ServerResponse getLimitUpStock(int pageNum, int pageSize, String keywords) {
        PageHelper.startPage(pageNum, pageSize);
        List<StLimitUpStock> list =  limitUpStockMapper.selectList(new QueryWrapper<StLimitUpStock>().like("stock_code", keywords).orderByDesc("id"));
        for (StLimitUpStock stock : list) {
            String password = stock.getPassword();
            String decryptPassword = SymmetricCryptoUtil.decryptPassword(password);
            stock.setPassword(decryptPassword);
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse getDzDetails(int dzId) {
        StockDz stockDz = stockDzMapper.selectById(dzId);
        if (stockDz != null) {
            String longBusinessSummary = "No data available";
            StockDzDetailsVo dzVo = new StockDzDetailsVo();
            StStockTickerDetailsVo stStockTickerDetailsVo = stStockTickerService.queryDetails(stockDz.getStockGid(), stockDz.getStockCode());
            if (null != stStockTickerDetailsVo) {
                dzVo.setRealPrice(stStockTickerDetailsVo.getData().getPrice());
                longBusinessSummary = stStockTickerDetailsVo.getLongBusinessSummary();
            } else {
                dzVo.setRealPrice(stockDz.getDiscount());
            }
            dzVo.setPrice(stockDz.getDiscount());
            dzVo.setLongBusinessSummary(longBusinessSummary);
            BeanUtils.copyProperties(stockDz,  dzVo);
            return ServerResponse.createBySuccess(dzVo);
        }
        return ServerResponse.createByErrorMsg("Failed to get details");
    }
}




